import { Login_Path } from "@/config";

let _debounceTimeout = null,
	_throttleRunning = false;

// 防抖
export const debounce = (fn, delay = 500) => {
	clearTimeout(_debounceTimeout);
	_debounceTimeout = setTimeout(() => {
		fn();
	}, delay);
};

//节流
export const throttle = (fn, delay = 500) => {
	if (_throttleRunning) {
		return;
	}
	_throttleRunning = true;
	fn();
	setTimeout(() => {
		_throttleRunning = false;
	}, delay);
};

/**
 * 跳转页面
 */
export const navTo = (url) => {
	throttle(() => {
		uni.navigateTo({
			url,
		});
	});
};

/**
 * 返回上一页
 */
export const navBack = (delta = 1) => {
	throttle(() => {
		uni.navigateBack({
			delta
		})
	});
};

/**
 * 跳转前检查是否登录
 */
export async function checkLogin(url) {
	const { data } = await checkLogin();
	if (data) {
		navTo(url);
	} else {
		uni.navigateTo({
			url: Login_Path,
		});
	}
}

// 返回上一个页面并改变data
export function prePage(key, value) {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2]; //上一个页面
	//#ifdef H5
	prePage[key] = value;
	//#endif
	//#ifdef MP-WEIXIN
	prePage.$vm[key] = value;
	//#endif
	uni.navigateBack({ delta: 1 });
}
